<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2019/11/21
 * Time: 10:00
 */

namespace App\Repository;


use App\Events\WorkshopCreated;
use App\Exceptions\ApiException;
use App\Interfaces\MapInterFace;
use App\Interfaces\WorkshopInterFace;
use App\Jobs\SendUserMini;
use App\model\City;
use App\model\panyuan\MyApply;
use App\model\panyuan\UserShenheLog;
use App\model\panyuan\UserShenheSum;
use App\model\panyuan\WorkshopLog;
use App\model\panyuan\WorkshopOverdue;
use App\model\UserWorkshopApply;
use App\model\Workshop;
use App\model\WorkshopIndustry;
use App\model\WorkshopShenhe;
use App\Service\BaiduMapService;
use App\Service\MiniProgramService;
use App\Service\MiniWorkService;
use App\User;
use App\UserShenhe;
use Geohash\GeoHash;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use \Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Support\Facades\Storage;
use phpDocumentor\Reflection\Types\This;
use function foo\func;
use function Qiniu\base64_urlSafeEncode;

class WorkShopRepository implements WorkshopInterFace
{
    protected $baiduMapService;
    protected  $miniWorkService;
    public function __construct(MapInterFace $baiduMapService,MiniWorkService $miniWorkService)
    {
        $this->miniWorkService=$miniWorkService;
        $this->baiduMapService = $baiduMapService;
    }

    /**
     * @param User $user
     * @param Request $request
     * @return Workshop
     */
    public function addDiskSource(User $user, Request $request): Workshop
    {

      $workshop=  new Workshop();
      $slider= $request->slider;

      $workshop->slider=json_encode($slider);
      $workshop->title=$request->title;
      $workshop->type=0;
      $workshop->user_id=$user->id;
      $workshop->owndesc=$request->owndesc;
      $workshop->rent=$request->rent=='面议' ? 0 : $request->rent; //租金
      $workshop->owner=$request->owner;//业主
      $workshop->ownertel=$request->owner_tel;//业主电话
      $workshop->area=$request->area;//面积
      $workshop->address=$request->address;//地址
      $workshop->high=$request->high;//层高
      $workshop->floor=$request->floor;//所在楼层
      $workshop->certificates=$request->zhengjian_id;//证件
      $workshop->date_of_commission=$request->start_day;//委托开始日期
      $workshop->commission_end_day=$request->end_day;//委托结束日期
      $workshop->is_park=$request->is_park;
      $workshop->p_province_id=City::find($request->city_id)->parent_id ?? '';
      $workshop->p_city_id=$request->city_id;
      $workshop->p_district_id=$request->qu_id;
      $workshop->shenhe=Workshop::SHENHE;//审核
      $workshop->changfang_type=$request->changfang_type;
      $workshop->weight_id=$request->chengzhong_id;
      $workshop->shenhe_role_id=1;//提交采购审核
      $workshop->save();
     if ($request->industry)  {
         $workshop->industry()->sync(explode(',',$request->industry));
     }
    if ($request->hangye){
        $workshop->hangye()->sync(explode(',',$request->hangye));
    }
    if ($request->tags_id){
        $workshop->tags()->sync(explode(',',$request->tags_id));
    }


      return $workshop;
    }
    protected  function workshop(){

}
    /**
     * 编辑盘源
     */
    public function editDiskSource(User $user, Workshop $workshop,$request)
    {
        \DB::transaction(function()use($user,$workshop,$request){
            $slider= $request->slider;
            $desc='';

            $slider=json_encode($slider);


            if ($workshop->title!=$request->title){
                $desc.='标题:'.$request->title;
            }
            if ($workshop->owndesc!=$request->owndesc){
                $desc.='修改了内容';
            }
            if ($workshop->owner!=$request->owner){
                $desc.='业主姓名:'.$request->title;
            }
            if ($workshop->ownertel!=$request->owner_tel){
                $desc.='业主电话:'.$request->owner_tel;
            }
            if ($workshop->area!=$request->area){
                $desc.='面积:'.$request->area;
            }
            if ($workshop->address!=$request->address){
                $desc.='地址:'.$request->address;
            }
            if ($workshop->high!=$request->high){
                $desc.='层高:'.$request->high;
            }
            if ($workshop->floor!=$request->floor){
                $desc.='所在楼层:'.$request->floor;
            }
            if ( $workshop->certificates!=$request->zhengjian_id){
                $desc.='证件:'.Workshop::$certificatesMap[$request->zhengjian_id];
            }
            if($workshop->commission_end_day!=$request->end_day){
                $desc.='委托结束日期:'.$request->end_day;
            }
            if ($workshop->floor!=$request->floor){
                $desc.='所在楼层:'.$request->floor;
            }

            if ($workshop->shenhe===Workshop::SHENHE_REFUSE){
                $workshop->shenhe=Workshop::SHENHE;
                $workshop->save();
            }

            $code=$request->code;
            $myapply=MyApply::where('code',$code)->first();
            if (!$myapply){
                $code=$this->getCode($workshop);
                $myapply= new MyApply();
                $myapply->status=MyApply::SHENHE;
                $myapply->last_status=MyApply::SHENHE;
                $myapply->code=$code;
                $myapply->user_id=$user->id;
                $myapply->workshop_id=$workshop->id;
                $myapply->type=MyApply::Updated_panyuan;
                $myapply->save();
            }else{
                $myapply->status=MyApply::SHENHE;
                $myapply->last_status=MyApply::SHENHE;
                $myapply->save();
            }
            $workshop_log= new WorkshopLog();
            $workshop_log->user_id=$user->id;
            $workshop_log->workshop_id=$workshop->id;
            $workshop_log->value=serialize($request->all());
            $workshop_log->desc=$desc;
            $workshop_log->status=WorkshopLog::STATUS_SHENHE;
            $workshop_log->save();
            $userShenhe=new UserShenhe();
            $userShenhe->role_id=1;//采购审核
            $userShenhe->workshop_id=$workshop->id;
            $userShenhe->type=UserShenhe::Updated_panyuan;//更新盘源
            $userShenhe->status=UserShenhe::STATUS_SHENHE;
            $userShenhe->title=$user->name.'有一条更新盘源待你审核，请尽快处理';
            $userShenhe->code=$code;
            $userShenhe->user_id=$user->id;
            $userShenhe->is_read=0;
            $userShenhe->save();
            //查看过期的盘源
           $workshopOverdue= WorkshopOverdue::where('workshop_id',$workshop->id)->where('is_updated',WorkshopOverdue::NO_UPDATED)->first();
           if ($workshopOverdue){
               $workshopOverdue->is_updated=WorkshopOverdue::UPDATED;
               $workshopOverdue->code=$code;
               $workshopOverdue->save();
           }
            $this->editWorkshopNotice($user,$workshop,$code);
        });
    }

    /**
     * 管理员编辑房源
     * @param $request
     * @param $workshop
     * @return mixed
     */
    public function mangerUpdatedPanyuan($request,$workshop){
        $slider= $request['slider'];
        $workshop->slider=json_encode($slider);
        $workshop->title=$request['title'];
        $workshop->owndesc=$request['owndesc'];
        $workshop->rent=$request['rent']; //租金
        $workshop->owner=$request['owner'];//业主
        $workshop->ownertel=$request['owner_tel'];//业主电话
        $workshop->area=$request['area'];//面积
        $workshop->address=$request['address'];//地址
        $workshop->high=$request['high'];//层高
        $workshop->floor=$request['floor'];//所在楼层
        $workshop->certificates=$request['zhengjian_id'];//证件
        $workshop->date_of_commission=$request['start_day'];//委托开始日期
        $workshop->commission_end_day=$request['end_day'];//委托结束日期
        $workshop->is_park=$request['is_park'];
        $workshop->p_province_id=City::find($request['city_id'])->parent_id ?? '';
        $workshop->p_city_id=$request['city_id'];
        $workshop->p_district_id=$request['qu_id'];
        $workshop->changfang_type=$request['changfang_type'];
        $workshop->weight_id=$request['chengzhong_id'];
        $workshop->save();

        if (isset($request['industry']))  {
            $workshop->industry()->sync(explode(',',$request['industry']));
        }
        if (isset($request['hangye'])){
            $workshop->hangye()->sync(explode(',',$request['hangye']));
        }
        if (isset($request['tags_id'])){
            $workshop->tags()->sync(explode(',',$request['tags_id']));
        }
        return $workshop;
    }
    /**
     * 审核
     */
    public function updatedPanyuan(User $user,UserShenhe $userShenhe,Workshop $workshop){
       $workshopLog= WorkshopLog::where('workshop_id',$workshop->id)->where('status',WorkshopLog::STATUS_SHENHE)->first();
       if (!$workshopLog){
           throw new ApiException('没有审核记录');
       }

       \DB::transaction(function ()use($userShenhe,$user,$workshop,$workshopLog){
           if ($user->role_id==1){
               $userShenheLog=new UserShenheLog();
               $userShenheLog->code=$userShenhe->code;
               $userShenheLog->status=UserShenheLog::STATUS_PASS;
               $userShenheLog->user_id=$user->id;
               $userShenheLog->role_id=$user->role_id;
               $userShenheLog->save();
               $userShenhe->status=$userShenhe::STATUS_TONGYI;
               $userShenhe->save();
               $users=new UserShenhe();
               $users->role_id=2;//发布审核
               $users->workshop_id=$workshop->id;
               $users->type=UserShenhe::Updated_panyuan;//更新盘源
               $users->status=UserShenhe::STATUS_SHENHE;
               $users->title=$userShenhe->title;
               $users->code=$userShenhe->code;
               $users->user_id=$userShenhe->user_id;
               $users->is_read=0;
               $users->save();
               $this->editWorkshopNotice(User::find($userShenhe->user_id),$workshop,$userShenhe->code,2);
               $myapply=MyApply::where('code',$userShenhe->code)->first();
               if ($myapply){

                   $myapply->last_status=MyApply::SHENHE_YEWU_PULISHED;
                   $myapply->save();
               }
               return ;
           }
           $request=unserialize($workshopLog->value);
           $slider= $request['slider'];
           $workshop->slider=json_encode($slider);
           $workshop->title=$request['title'];
           $workshop->owndesc=$request['owndesc'];
           $workshop->rent=$request['rent']; //租金
           $workshop->owner=$request['owner'];//业主
           $workshop->ownertel=$request['owner_tel'];//业主电话
           $workshop->area=$request['area'];//面积
           $workshop->address=$request['address'];//地址
           $workshop->high=$request['high'];//层高
           $workshop->floor=$request['floor'];//所在楼层
           $workshop->certificates=$request['zhengjian_id'];//证件
           $workshop->date_of_commission=$request['start_day'];//委托开始日期
           $workshop->commission_end_day=$request['end_day'];//委托结束日期
           $workshop->is_park=$request['is_park'];
           $workshop->p_province_id=City::find($request['city_id'])->parent_id ?? '';
           $workshop->p_city_id=$request['city_id'];
           $workshop->p_district_id=$request['qu_id'];
           $workshop->changfang_type=$request['changfang_type'];
           $workshop->weight_id=$request['chengzhong_id'];
           $workshop->save();
           if (isset($request['industry']))  {
               $workshop->industry()->sync(explode(',',$request['industry']));
           }
           if (isset($request['hangye'])){
               $workshop->hangye()->sync(explode(',',$request['hangye']));
           }
           if (isset($request['tags_id'])){
               $workshop->tags()->sync(explode(',',$request['tags_id']));
           }
           $myapply=MyApply::where('code',$userShenhe->code)->first();
           if ($myapply){
               $myapply->status=MyApply::SHENHE_PULISHED;
               $myapply->last_status=MyApply::SHENHE_PULISHED;
               $myapply->save();
           }
           //更新盘源
           $workshopLog->status=WorkshopLog::STATUS_PASS;
           $workshopLog->save();
           $userShenheLog=new UserShenheLog();
           $userShenheLog->code=$userShenhe->code;
           $userShenheLog->status=UserShenheLog::STATUS_PASS;
           $userShenheLog->user_id=$user->id;
           $userShenheLog->role_id=$user->role_id;
           $userShenheLog->save();
           $userShenhe->status=$userShenhe::STATUS_TONGYI;
           $userShenhe->save();
           $users=  new UserShenhe();
           switch ($userShenhe->type){
               case UserShenhe::Created_panyuan:
                   $users->title='发布盘源通过';
                   break;
               case UserShenhe::View_panyuan:
                   $users->title='查看业主通过';
                   break;
               case UserShenhe::Updated_panyuan:
                   $users->title='编辑盘源通过';
                   break;
           }
           $users->type=$userShenhe->type;
           $users->role_id=3;
           $users->status=UserShenhe::STATUS_TONGYI;
           $users->user_id=$myapply->user_id;
           $users->code=$userShenhe->code;
           $users->workshop_id=$workshop->id;
            $users->save();
          UserShenheSum::delSum($myapply->user_id);
          $workshopOverdue=  WorkshopOverdue::where('code',$userShenhe->code)->first();
          if ($workshopOverdue){
              $workshopOverdue->is_shenhe=WorkshopOverdue::SHENHE;
              $workshopOverdue->save();
          }
           dispatch(new SendUserMini(User::find($myapply->user_id),[
               'title'=>$users->title,
               'url'=>'pages/xiaoxi/shenpi/detail/index?id=0&code='.$userShenhe->code,
               'content_item'=>[
               ]
           ]));

       });

    }
    /**
     * 审核通过
     */
    public function diskSourcePassed(User $user,Workshop $disksource,UserShenhe $userShenhe)
    {
            \DB::transaction(function ()use($disksource,$user,$userShenhe){
                if ($disksource->shenhe_role_id==2){
                    $disksource->shenhe=Workshop::SHENHE_PULISHED;
                    $disksource->is_published=Workshop::PUBLISED;
                    $disksource->save();
                    $myapply=MyApply::where('code',$userShenhe->code)->first();
                    if ($myapply){
                        $myapply->status=MyApply::SHENHE_PULISHED;

                        $myapply->last_status=MyApply::SHENHE_PULISHED;
                        $myapply->save();
                    }
                    //推送成功审核
                    $this->pass(User::find($disksource->user_id),$userShenhe,$disksource);
                   // UserShenheSum::addsum($disksource->user_id);
                    event(new  \App\Events\WorkshopShenhe($userShenhe));
                }
                if ($disksource->shenhe_role_id==1){
                    $disksource->shenhe_role_id=2;
                    $disksource->save();
                    //推送给推广员
                    $myapply=MyApply::where('code',$userShenhe->code)->first();
                    if ($myapply){
                        $myapply->last_status=MyApply::SHENHE_YEWU_PULISHED;
                        $myapply->save();
                    }
                    $userS=new UserShenhe();
                    $userS->user_id=$userShenhe->user_id;
                    $userS->workshop_id=$userShenhe->workshop_id;
                    $userS->code=$userShenhe->code;
                    $userS->title=User::find($userShenhe->user_id)->name.'有一条盘源发布待审核，请尽快处理';
                    $userS->type=UserShenhe::Created_panyuan;
                    $userS->role_id=2;
                    $userS->status=UserShenhe::STATUS_SHENHE;
                    $userS->save();
                    $this->CreateWorkshopNotice($disksource,$userShenhe->code);

                }
                $userShenheLog=new UserShenheLog();
                $userShenheLog->code=$userShenhe->code;
                $userShenheLog->status=UserShenheLog::STATUS_PASS;
                $userShenheLog->user_id=$user->id;
                $userShenheLog->role_id=$user->role_id;
                $userShenheLog->save();
                $userShenhe->status=$userShenhe::STATUS_TONGYI;
                $userShenhe->save();
            });
            return $disksource;

    }
    public function passView(User $user,UserShenhe $userShenhe,Workshop $workshop){
        \DB::transaction(function ()use($user ,$userShenhe,$workshop){
            $userWorkShopApply=new UserWorkshopApply();
            $userWorkShopApply->user_id=$userShenhe->user_id;
            $userWorkShopApply->workshop_id=$userShenhe->workshop_id;
            $userWorkShopApply->save();
            $myapply=MyApply::where('code',$userShenhe->code)->first();
            if ($myapply){
                $myapply->status=MyApply::SHENHE_PULISHED;
                $myapply->last_status=MyApply::SHENHE_PULISHED;
                $myapply->save();
            }
            $userShenhe->status=UserShenhe::STATUS_TONGYI;
            $userShenhe->save();
            $userShenheLog=new UserShenheLog();
            $userShenheLog->code=$userShenhe->code;
            $userShenheLog->status=UserShenheLog::STATUS_PASS;
            $userShenheLog->user_id=$user->id;
            $userShenheLog->role_id=$user->role_id;
            $userShenheLog->save();
            $users=  new UserShenhe();
            $users->title='查看业主通过';
            $users->type=$userShenhe->type;
            $users->role_id=3;
            $users->status=UserShenhe::STATUS_TONGYI;
            $users->user_id=$userShenhe->user_id;
            $users->code=$userShenhe->code;
            $users->workshop_id=$workshop->id;
            $users->save();
            UserShenheSum::delSum($userShenhe->user_id);
            dispatch(new SendUserMini(User::find($userShenhe->user_id),[
                'title'=>$users->title,
                'url'=>'pages/xiaoxi/shenpi/detail/index?id=0&code='.$userShenhe->code,
                'content_item'=>[
                ]
            ]));
        });
    }
    protected function pass(User $user,UserShenhe $userShenhe,Workshop $workshop){
        $users=  new UserShenhe();
        switch ($userShenhe->type){
            case UserShenhe::Created_panyuan:
                $users->title='发布盘源通过';
                break;
            case UserShenhe::View_panyuan:
                $users->title='查看业主通过';
                break;
            case UserShenhe::Updated_panyuan:
                $users->title='编辑盘源通过';
                break;
        }
        $users->type=$userShenhe->type;
        $users->role_id=3;
        $users->status=UserShenhe::STATUS_TONGYI;
        $users->user_id=$workshop->user_id;
        $users->code=$userShenhe->code;
        $users->workshop_id=$workshop->id;
        $users->save();

        dispatch(new SendUserMini($user,[
            'title'=>$users->title,
            'url'=>'pages/xiaoxi/shenpi/detail/index?id=0&code='.$userShenhe->code,
            'content_item'=>[
            ]
        ]));
    }
    protected function refuse(User $user,UserShenhe $userShenhe,$refuseReason,Workshop $workshop){
      $users=  new UserShenhe();
      switch ($userShenhe->type){
          case UserShenhe::Created_panyuan:
              $users->title='发布盘源不通过';
              $users->refuseReason=$refuseReason;
              break;
          case UserShenhe::View_panyuan:
              $users->title='查看业主不通过';
              $users->refuseReason=$refuseReason;
              break;
          case UserShenhe::Updated_panyuan:
              $users->title='编辑盘源不通过';
              $users->refuseReason=$refuseReason;
              break;
        }
        $myapply=MyApply::where('code',$userShenhe->code)->first();
        if ($myapply){
            $myapply->status=MyApply::SHENHE_REFUSE;
            $myapply->last_status=$user->role_id==1 ? MyApply::SHENHE_YEWU_REFUSE : MyApply::SHENHE_REFUSE;
            $myapply->save();
        }
        $users->type=$userShenhe->type;
        $users->role_id=3;
        $users->status=UserShenhe::STATUS_JUJUE;
        $users->user_id=$userShenhe->user_id;
        $users->workshop_id=$workshop->id;
        $users->code=$userShenhe->code;
        $users->save();

        $userShenhe->status=UserShenhe::STATUS_JUJUE;;
        $userShenhe->refuseReason=$refuseReason;
        $userShenhe->save();
        $userShenheLog=new UserShenheLog();
        $userShenheLog->code=$userShenhe->code;
        $userShenheLog->status=UserShenheLog::STATUS_REJECT;
        $userShenheLog->reject_reason=$users->refuseReason;
        $userShenheLog->user_id=$user->id;
        $userShenheLog->role_id=$user->role_id;
        $userShenheLog->save();
        dispatch(new SendUserMini(User::find($userShenhe->user_id),[
            'title'=>$users->title,
            'url'=>'pages/xiaoxi/shenpi/detail/index?id=0&code='.$userShenhe->code,
            'content_item'=>[
               [ 'key'=>'原因',
                    'value'=>$users->refuseReason
               ]
            ]
        ]));
    }
    /**
     * 审核盘源不通过
     */
    public function diskSourceRefuse(User $user,Workshop $disksource,UserShenhe $userShenhe,$refuseReason)
    {
        //盘源状态变为拒绝
        $disksource->shenhe_role_id=1;//采购员
        $disksource->shenhe=Workshop::SHENHE_REFUSE;
        $disksource->save();
        $this->refuse($user,$userShenhe,$refuseReason,$disksource);
    }
    /**
     * 查看业主不通过
     */
    public function viewSourceRefuse(User $user,Workshop $disksource,UserShenhe $userShenhe,$refuseReason){
        $this->refuse($user,$userShenhe,$refuseReason,$disksource);
    }
    /**
     *
     */
    public function updateSourceRefuse(User $user,Workshop $disksource,UserShenhe $userShenhe,$refuseReason){
       $workshopLog=  WorkshopLog::where('workshop_id',$disksource->id)->where('status',WorkshopLog::STATUS_SHENHE)->first();
       if ($workshopLog){
           $workshopLog->status=WorkshopLog::STATUS_REJECT;
           $workshopLog->save();
       }
        $this->refuse($user,$userShenhe,$refuseReason,$disksource);
    }

    /**
     * 同步到官网
     */
    public function syncWebsite(Workshop $disksource): bool
    {

    }

    /**
     * 创建房源审核成功推送给个人
     */
    public function allUserNotice(Workshop $disksource): bool
    {


    }
    /**
     * 创建房源推送
     */
    public function CreateWorkshopNotice(Workshop $workshop,$code){


        $users=User::where('role_id',$workshop->shenhe_role_id)->get();
        foreach ($users as $user){
            dispatch(new SendUserMini($user,[
                'title'=>'有一条盘源发布待审核',
                'url'=>'pages/xiaoxi/shenpi/detail/index?id=0&code='.$code,
                'content_item'=>[
                    [
                        'key'=>'申请人',
                        'value'=>User::find($workshop->user_id)->name ?? ''
                ]
                    ]
            ]));

        }
    }
    /**
     *申请推送
     */
    public function applyWorkshopNotice(User $user,Workshop $workshop,$code){

        $users=User::where('role_id',1)->get();
        foreach ($users as $item){
            //todo
            dispatch(new SendUserMini($item,[
                'title'=>'申请业主待审核',
                'url'=>'pages/xiaoxi/shenpi/detail/index?id=0&code='.$code,
                'content_item'=>[
                    [
                        'key'=>'申请人',
                        'value'=>$user->name
                    ]
                ]
            ]));
        }
    }
    /**
     * 更新盘源推送
     */
    public function editWorkshopNotice(User $user,Workshop $workshop,$code,$role_id=1){
        $users=User::where('role_id',$role_id)->get();
        foreach ($users as $item){
            //todo
            dispatch(new SendUserMini($item,[
                'title'=>'更新盘源待审核',
                'url'=>'pages/xiaoxi/shenpi/detail/index?id=0&code='.$code,
                'content_item'=>[
                    [
                        'key'=>'申请人',
                        'value'=>$user->name
                    ]
                ]
            ]));
        }
    }
    /**
     * 录入盘源提醒
     */
    public function addDiskSourceNotice(Workshop $disksource): bool
    {


    }

    /**
     * 审核不通过收到提醒
     */
    public function refuseDiskSourceNotice(Workshop $disksource): bool
    {

    }

    /**
     * 盘源列表
     */
    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|Paginator
     */
    public function DiskSourceList(Request $request): Paginator
    {

        $sort_key = $request->get('sort_key', 'id');
        $sort=$request->get('sort','desc');
        $province_id = $request->get('province_id', '');
        $city_id = $request->get('city_id', '');
        $qu_id = $request->get('qu_id', '');
        $tags = $request->get('tags', '');
        $hangye = $request->get('hangye', '');
        $industry = $request->get('industry', '');
        $purpose = $request->get('purpose', '');
        $area=$request->get('area','');
        $status=$request->get('status');
        $floor=$request->get('floor');
        $type=$request->get('type');
        $workshop = Workshop::with('hangye', 'qu', 'industry', 'tags','park');
        $workshop=$workshop->orderBy('is_zhiding','desc');
        if ($sort_key) {
            $workshop = $workshop->orderBy($sort_key,$sort);
        };
        if ($type){
            $workshop=$workshop->where('type',$type);
        }
        if ($province_id) {
            $workshop = $workshop->where('p_province_id', $province_id);
        }
        if ($city_id) {
            $workshop = $workshop->where('p_city_id', $city_id);
        }
        if ($qu_id) {
            $workshop = $workshop->where('p_district_id', $qu_id);
        }
        if ($floor){
            $workshop=$workshop->where('floor', $floor);
        }
        //标签
        if ($tags) {
            $workshop = $workshop->whereHas('tags', function ($builder) use ($tags) {
                $tags = explode(',', $tags);
                $builder->whereIn('workshop_tag.id', $tags);
            });
        }
        //行业
        if ($hangye) {
            $workshop = $workshop->whereHas('hangye', function ($builder) use ($hangye) {
                $hangye = explode(',', $hangye);
                $builder->whereIn('workshop_hangye.id', $hangye);
            });
        }
        //类型
        if ($industry) {
            $workshop = $workshop->whereHas('industry', function ($builder) use ($industry) {
                $industry = explode(',', $industry);
                $builder->whereIn('workshop_industry.id', $industry);
            });
        }
        //用途
        if ($purpose) {
            if ($purpose==5){//查询用途仓库顺便查询类型
                $workshop = $workshop->where(function ($query)use($purpose){
                    $query->whereHas('purpose', function ($builder) use ($purpose) {
                        $purpose = explode(',', $purpose);
                        $builder->whereIn('workshop_purpose.id', $purpose);
                    })->orWhereHas('industry', function ($builder)  {
                        $builder->where('workshop_industry.id', 8);
                    });
                });
            }else{
                $workshop = $workshop->whereHas('purpose', function ($builder) use ($purpose) {
                    $purpose = explode(',', $purpose);
                    $builder->whereIn('workshop_purpose.id', $purpose);
                });
            }

        }
        //面积
        if ($area){

            switch ($area) {
                case 1:
                    $workshop = $workshop->where('area', '<', 1000);
                    break;
                case 2:
                    $workshop = $workshop->where('area', '>=', 1000)
                        ->where('area', '<=', 3000);
                    break;
                case  3:
                    $workshop = $workshop->where('area', '>=', 3000)
                        ->where('area', '<=', 6000);
                    break;
                case  4:
                    $workshop = $workshop->where('area', '>=', 6000)
                        ->where('area', '<=', 10000);
                    break;
                case  5:
                    $workshop = $workshop->where('area', '>=', 10000);
                    break;
            }
        }
        //状态
        if ($status!==""&&$status!==null){
            $workshop=$workshop->where('status',$status);
        }
        return $workshop->paginate(10);
    }

    /**
     * 附近的盘源
     */
    public function DiskSourceNear(Workshop $disksource): Collection
    {

    }
    /**
     *
     */
    public function workshopRecommd($limit){
        $workshop = Workshop::with('hangye', 'qu', 'industry', 'tags')
            ->orderBy('is_zhiding','desc')
            ->orderByDesc('is_recommend', 'desc')
            ->orderByDesc('id', 'desc')
            ->take($limit)
            ->get();
        return $workshop;
    }
    public function detail($id){
        $workshop = Workshop::with('hangye', 'industry', 'tags', 'qu', 'zhen','park')->where('id', $id)->first();
        return $workshop;
    }
    /**
     * 获取经纬度
     * @param Workshop $workshop
     * @return bool
     */
    public function DiskSourceGeo(Workshop $workshop): bool
    {

        $city = $workshop->city->title ?? '';
        $qu=$workshop->qu->title ?? '';
        $zhen=$workshop->zhen->title ?? '';

        $address = $workshop->address;
        list($latitude, $longitude) = $this->baiduMapService->geocoding($city.$qu.$zhen.$address, $city);
        $GeoHash = new GeoHash();
        $geo = $GeoHash->encode($latitude, $longitude);
        $workshop->latitude = $latitude;
        $workshop->longitude = $longitude;
        $workshop->geo = $geo;
        $workshop->save();
        return true;
    }
    static function setSlider($workshop){
        $slider=json_decode($workshop->slider,true);
        collect($slider)->each(function ($item){
            $filename= pathinfo($item['img'],PATHINFO_EXTENSION);
            $path=md5($item['img']).'.'.$filename;
            if(!Storage::exists($path)){
                $slider=Storage::put($path,file_get_contents($item['img'].'?watermark/1/image/'.base64_urlSafeEncode('http://pic.qalex.com/images/mater.png?imageView2/2/w/150/h/150').'/dissolve/80/gravity/NorthEast'));
            }
        });
    }
    static function getSlider($url)
    {
        $filename = pathinfo($url, PATHINFO_EXTENSION);
        $path = md5($url) . '.' . $filename;
        return Storage::url($path);
    }
    public function removeWorkshopDescStyle($workshop){
        $res = preg_replace('/style=".*?"/i', '', $workshop->owndesc);
        $res = str_replace("<strong>", '', $res);
        $res = str_replace("</strong>", '', $res);
        $workshop->owndesc=$res;
        $workshop->save();
    }
    /**
     * @param Workshop $workshop
     * @param \App\model\agent\Agent $agent
     */
    public function miniQrcode(Workshop $workshop, \App\model\agent\Agent $agent)
    {
        $filename=$workshop->id.'miniQrcode'.$agent->id;
        if (!Storage::exists($filename)) {
            $serviec = new MiniProgramService();
            $value = $agent->id . '&' . $workshop->id;
            $qrcode = $serviec->miniCode($value, 'pages/detail/detail');
            $slider = collect(json_decode($workshop->slider, true))->reject(function ($value) {
                return $value['isDisplay'] == 0;
            })->map(function ($value) {
                return $value['img'];
            })->toArray();
            $slider=array_values($slider);
            $img = \Intervention\Image\Facades\Image::canvas(1000, 1639, '#fff');
            //top横条图
            $img->insert('http://pic.qalex.com/file/4wmXpSU4JfM1N35f9kkjn4wszCslZHzIejeZ63lj.png?imageView2/0/w/1000/h/180');
            //图像1
            $image1 = \Intervention\Image\Facades\Image::make($slider[0] . '?imageView2/1/w/960/h/550|roundPic/radius/25');
            $image1->resize(960, 550);
            $img->insert($image1, 'top-left', 20, 204);
            //印章
            $imageYinZhang = \Intervention\Image\Facades\Image::make('http://pic.qalex.com/file/7XHjTWegCAipEwDz2rRyVNw4LXRLLRhM2sv2oTjB.png');
            $img->insert($imageYinZhang, 'top-left', 0, 0);
            //图像2
            $image2 = \Intervention\Image\Facades\Image::make($slider[1] . '?imageView2/1/w/475/h/280|roundPic/radius/25');
            $image2->resize(475, 280);
            $img->insert($image2, 'top-left', 20, 770);
            //图像3
            $image3 = \Intervention\Image\Facades\Image::make($slider[2] . '?imageView2/1/w/475/h/280|roundPic/radius/25');
            $image3->resize(475, 280);
            $img->insert($image3, 'top-left', 510, 770);
            //图像4
            $image4 = \Intervention\Image\Facades\Image::make($slider[3] . '?imageView2/1/w/475/h/280|roundPic/radius/25');
            $image4->resize(475, 280);
            $img->insert($image4, 'top-left', 20, 1065);
            //图像5
            $image5 = \Intervention\Image\Facades\Image::make($slider[4] . '?imageView2/1/w/475/h/280|roundPic/radius/25');
            $image5->resize(475, 280);
            $img->insert($image5, 'top-left', 510, 1065);
            //底部背景
            $image6 = \Intervention\Image\Facades\Image::make('http://pic.qalex.com/file/v4e2lvH4CZ39sXeCoXdj6nSmHvc0bmzmhurHok6s.png?imageMogr2/crop/!1000x282a0a1338');
            $img->insert($image6, 'top-left', 0, 1370);
            //椭圆图片
            $tuoyuan = \Intervention\Image\Facades\Image::make('http://pic.qalex.com/file/9MZ7pmHJXTuoYHcOshu463WqofllmxuK1in5FtHl.png');
            $img->insert($tuoyuan, 'top-left', 700, 1311);
            //二维码背景
            $qrcodeBg = \Intervention\Image\Facades\Image::make('http://pic.qalex.com/file/MMU1v0BZr6HhcS88GhgowmuHUpXsmsGw3z8o2ppp.png');
            $img->insert($qrcodeBg, 'top-left', 710, 1321);
            //二维码图片
            $qrcode = \Illuminate\Support\Facades\Storage::url($qrcode) . '?roundPic/radius/200';
            $qrcode = \Intervention\Image\Facades\Image::make($qrcode);
            $qrcode->resize(205, 205);
            $img->insert($qrcode, 'top-left', 723, 1338);
            //厂房标题
            $title1 = \Illuminate\Support\Str::limit($workshop->title, 26, '');
            $title2 = \Illuminate\Support\Str::after($workshop->title, $title1);
            $img->text($title1, 31, 1486, function (\Intervention\Image\AbstractFont $font) {
                $font->file(public_path('fonts/msyh.ttf'));
                $font->size(40);
                $font->color('#ffffff');
            });
            $img->text($title2, 31, 1552, function (\Intervention\Image\AbstractFont $font) {
                $font->file(public_path('fonts/msyh.ttf'));
                $font->size(40);
                $font->color('#ffffff');
            });
            $img->text('长按识别了解厂房详情', 705, 1602, function (\Intervention\Image\AbstractFont $font) {
                $font->file(public_path('fonts/msyh.ttf'));
                $font->size(25);
                $font->color('#ffffff');
            });
            Storage::put($filename, $img->response()->getContent());
        }
        return Storage::url($filename);
    }

    /**
     * 审核编码
     */
    public function getCode(Workshop $workshop)
    {
         return date("YmdHis",time()).$workshop->id;
    }
}
